package com.feng.config;

import com.feng.pojo.User;
import com.feng.service.UserService;
import com.feng.service.UserServiceImpl;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

public class UserRealm extends AuthorizingRealm {

    //自动注入用户信息
    @Autowired
    UserServiceImpl userService;

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行了授权方法：doGetAuthorizationInfo");
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
//        info.addStringPermission("user:add");

        //获取当前登录的用户
        Subject subject = SecurityUtils.getSubject();
        User currentUser = (User)subject.getPrincipal();//获取到user对象

        //获取数据库中用户权限的属性值，根据此值判断是否有相应的权限，add、update...
        info.addStringPermission(currentUser.getPerms());

        return info;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("执行了认证方法：doGetAuthenticationInfo");
        //自定义用户名和密码，用于测试用户名密码认证是否成功
       /* String user = "root";
        String password = "123";*/
        UsernamePasswordToken userToken = (UsernamePasswordToken)authenticationToken;
        User user = userService.queryUserByName(userToken.getUsername());
        if(user==null){
            return null;
        }

        //添加session判断是否已经登录过了，如果登录过了就不再显示登录按钮
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        session.setAttribute("loginUser",user);

        //密码验证
        return new SimpleAuthenticationInfo(user,user.getPassword(),"");
    }
}
